<?php


declare(strict_types=1);

namespace app\eslib;

/**
 * 调试助手
 * @version 1.0.1
 */
class DebugHelper
{
    /**
     * 文件版本号
     */
    const VERSION = '1.0.1'; // 增加实例方法 appendLog()

    private $logFileName = 'debug.txt';
    public function setLogFile($filename)
    {
        $this->logFileName = $filename;
    }
    public function writeLog($message)
    {
        self::log($message, $this->logFileName);
    }
    public function appendLog($message)
    {
        self::log($message, $this->logFileName, true);
    }
    /**
     * 返回微妙时间
     */
    public static function microtime()
    {
        return microtime(true);
    }
    /**
     * 返回性能计时结果
     */
    public static function elapsedTime($time1, $format = '耗时：%.3f 秒')
    {
        return sprintf($format, microtime(true) - $time1);
    }

    public static function log($message, $fileName = 'debug.log', $isAppend = false)
    {
        // integer、double、string、array、object、unknown type。
        switch (gettype($message)) {
            case 'array':
                $message = print_r($message, true);
                break;
            case 'object':
                $message = var_export($message, true);
                break;
            default:
                break;
        }
        $message = date('Y-m-d H:i:s') . PHP_EOL . $message . PHP_EOL;
        if ($isAppend) {
            file_put_contents(runtime_path() . $fileName, $message, FILE_APPEND);
        } else {
            file_put_contents(runtime_path() . $fileName, $message);
        }
    }
    public static function showTable($list)
    {
        if (!$list) {
            echo '<div class="table-container unfound">查无记录！</div>';
            return;
        }
        echo '<div class="table-container"><table class="table table-sm table-striped table-bordered table-hover" border="0" cellspacing="0" cellpadding="0">';
        $i = 0;
        foreach ($list as $row) {
            if ($i < 1) {
                echo '<tr>';
                foreach ($row as $k => $v) {
                    echo '<th>', $k, '</th>';
                }
                echo '</tr>';
            }
            echo '<tr>';
            foreach ($row as $k => $v) {
                echo '<td class="td_', $k, '"><div>', $v, '</div></td>';
            }
            echo '</tr>';
            $i++;
        }
        echo '</table></div>';
    }
}
